<?php
/**
 * Created by PhpStorm.
 * User: edmmss
 * Date: 2019/1/28
 * Time: 09:46
 */

namespace app\modules\repository;


class PostRepository
{
    private $_persistence;

    public function __construct(MemoryStorage $persistence)
    {
        $this->_persistence = $persistence;
    }

    public function findById(int $id): Post
    {
        $data = $this->_persistence->retrieve($id);

        if (is_null($data)) {
            throw new \InvalidArgumentException(sprintf('Post with ID %d does not exist', $id));
        }

        return Post::fromState($data);
    }

    public function save(Post $post)
    {
        $id = $this->_persistence->persist([
            'text'  => $post->getText(),
            'title' => $post->getTitle(),
        ]);

        $post->setId($id);
    }
}